from flask import Flask, request, jsonify
from flask_cors import CORS
import json
from datetime import datetime, timedelta
import networkx as nx
import pandas as pd
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from backend.path_optimizer import PathOptimizer
from backend.data_collector import DataCollector
from config import EXTERNAL_APIS

app = Flask(__name__)
CORS(app)

# 初始化组件
path_optimizer = PathOptimizer()
data_collector = DataCollector()

@app.route('/api/search', methods=['POST'])
def search_routes():
    """
    搜索最优路径
    """
    try:
        data = request.get_json()
        origin = data.get('origin')
        destination = data.get('destination')
        departure_date = data.get('departure_date')
        optimization_type = data.get('optimization_type', 'time')  # time, price, comfort
        
        # 获取交通数据
        transport_data = data_collector.get_transport_data(origin, destination, departure_date)
        
        # 路径优化
        optimal_routes = path_optimizer.find_optimal_routes(
            origin, destination, departure_date, transport_data, optimization_type
        )
        
        return jsonify({
            'success': True,
            'routes': optimal_routes,
            'message': f'找到 {len(optimal_routes)} 条最优路线'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/chat', methods=['POST'])
def chat():
    """
    AI对话接口
    """
    try:
        data = request.get_json()
        user_message = data.get('message')
        
        # 解析用户意图
        intent = path_optimizer.parse_user_intent(user_message)
        
        if intent['type'] == 'route_search':
            # 执行路径搜索
            routes = path_optimizer.find_optimal_routes(
                intent['origin'], intent['destination'], 
                intent['departure_date'], 
                data_collector.get_transport_data(
                    intent['origin'], intent['destination'], intent['departure_date']
                ),
                intent.get('optimization_type', 'time')
            )
            
            response = path_optimizer.generate_route_response(routes, intent)
        else:
            response = "我可以帮您查询最优出行路线，请告诉我您的出发地、目的地和出发时间。"
        
        return jsonify({
            'success': True,
            'response': response,
            'intent': intent
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/cities', methods=['GET'])
def get_cities():
    """
    获取支持的城市列表
    """
    cities = data_collector.get_supported_cities()
    return jsonify({
        'success': True,
        'cities': cities
    })

@app.route('/api/geocode', methods=['POST'])
def geocode():
    """
    地理编码：将地址转换为经纬度
    """
    try:
        data = request.get_json()
        address = data.get('address')
        
        if not address:
            return jsonify({'success': False, 'error': '地址不能为空'}), 400
        
        # 检查是否启用了高德地图API
        if EXTERNAL_APIS['GAODE']['ENABLED'] and data_collector.gaode_api:
            coordinates = data_collector.gaode_api.geocode(address)
            if coordinates:
                return jsonify({
                    'success': True,
                    'coordinates': {
                        'lng': coordinates[0],
                        'lat': coordinates[1]
                    }
                })
        
        # 如果API未启用或失败，返回模拟数据
        return jsonify({
            'success': True,
            'coordinates': {
                'lng': 116.397,  # 北京天安门
                'lat': 39.916
            },
            'message': '使用模拟数据（请启用高德地图API获取真实坐标）'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/poi', methods=['POST'])
def search_poi():
    """
    搜索兴趣点（POI）
    """
    try:
        data = request.get_json()
        keyword = data.get('keyword')
        city = data.get('city')
        
        if not keyword:
            return jsonify({'success': False, 'error': '搜索关键词不能为空'}), 400
        
        # 检查是否启用了高德地图API
        if EXTERNAL_APIS['GAODE']['ENABLED'] and data_collector.gaode_api:
            pois = data_collector.gaode_api.search_poi(keyword, city)
            return jsonify({
                'success': True,
                'pois': pois
            })
        
        # 如果API未启用，返回模拟数据
        mock_pois = [
            {
                'name': f'{keyword}（模拟）',
                'address': '北京市朝阳区',
                'location': '116.397,39.916',
                'type': '商务住宅'
            }
        ]
        
        return jsonify({
            'success': True,
            'pois': mock_pois,
            'message': '使用模拟数据（请启用高德地图API获取真实POI）'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/weather', methods=['GET'])
def get_weather():
    """
    获取天气信息
    """
    try:
        city = request.args.get('city')
        
        if not city:
            return jsonify({'success': False, 'error': '城市参数不能为空'}), 400
        
        # 检查是否启用了高德地图API
        if EXTERNAL_APIS['GAODE']['ENABLED'] and data_collector.gaode_api:
            weather = data_collector.gaode_api.get_weather(city)
            if weather:
                return jsonify({
                    'success': True,
                    'weather': weather
                })
        
        # 如果API未启用，返回模拟数据
        mock_weather = {
            'city': city,
            'weather': '晴',
            'temperature': '22°C',
            'humidity': '65%',
            'wind': '东南风 3级'
        }
        
        return jsonify({
            'success': True,
            'weather': mock_weather,
            'message': '使用模拟数据（请启用高德地图API获取真实天气）'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/status', methods=['GET'])
def get_api_status():
    """
    获取API状态
    """
    status = {
        'gaode_api': EXTERNAL_APIS['GAODE']['ENABLED'],
        'train_api': EXTERNAL_APIS['12306']['ENABLED'],
        'flight_api': EXTERNAL_APIS['CTRIP']['ENABLED'],
        'ai_chat': EXTERNAL_APIS['OPENAI']['ENABLED']
    }
    
    return jsonify({
        'success': True,
        'status': status,
        'message': 'API状态查询成功'
    })

if __name__ == '__main__':
    print("启动AI路径优化助手后端服务...")
    print("服务地址: http://localhost:5000")
    app.run(debug=True, host='0.0.0.0', port=5000)